<template>
  <div class="channel-edit">
    <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">
      <van-cell title="我的频道" :border="false">
        <van-button plain size="mini" type="danger" v-model="editing" @click="editing = !editing">
            {{editing ? '取消': '编辑'}}
        </van-button>
      </van-cell>
      <van-grid>
        <van-grid-item  :class="{current: index === active}" @click="clickChannel(index)" v-for="(item,index) in channels" :key="item.id">
          <span>{{item.name}}</span>
          <van-icon v-show="editing && index !== 0" @click="clickDelChannel(item,index)" name="cross" class="btn"></van-icon>
        </van-grid-item>
      </van-grid>
    </div>
     <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false"></van-cell>
      <van-grid>
        <van-grid-item @click="clickAddChannel(item)" v-for="item in optionalChannels" :key="item.id">
          <span>{{item.name}}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { reqSetChannels } from '@/api/channels.js'
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
export default {
  name: 'ChannelEdit',
  props: {
    active: {
      type: Number, // 传递过来的数据，必须是number类型
      required: true, // 必填项，必须父传子传递这个属性
      default: 0 // 默认值
    }
  },
  data () {
    return {
      editing: false
    }
  },
  async created () {
    await this.getAllChannelsAsync()
  },
  computed: {
    ...mapState(['channels']),
    ...mapGetters(['optionalChannels'])
  },
  methods: {
    ...mapActions(['getAllChannelsAsync']),
    ...mapMutations(['addChannel', 'delChannel']),
    clickChannel (index) {
      this.$emit('update-curChannel', index)
    },
    // 点击添加频道
    clickAddChannel (channel) {
      // 1.将选择channel数据往我的频道 channel 添加(不要操作vuex中的数据，要提交mutation)
      this.addChannel(channel)
      this.resetChannel()
    },
    // 点击删除频道
    clickDelChannel (channel, index) {
      // 如果点击删除的是在高亮前的，则需要this.active -1
      if (index < this.active) {
        this.$emit('update-active', this.active - 1)
      }
      // 如果点击删除的当前高亮，则默认回到第一项
      if (this.active === index) {
        this.$emit('update-active', 0)
      }

      this.delChannel(channel)
      this.resetChannel()
    },
    // 封装删除添加频道请求
    async resetChannel () {
      // 2.组装接口需要的数据
      const channelList = this.channels.map((item, index) => {
        return {
          id: item.id,
          seq: index
        }
      })
      // 去掉推荐频道，由于推荐频道是在第一个位置，所以这里直接删除第一个
      channelList.shift()
      // 3.发送重置式请求
      await reqSetChannels(channelList)
    }
  }
}
</script>

<style lang="scss" scoped>
.channel{
  padding:15px;
  font-size:14px;
  ::v-deep .van-button--mini {
    height: 22px;
    min-width: 50px;
  }
  .btn {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 14px;
  }
  .current{
      color: #ee0a24;
      font-weight: bold;
  }
}
</style>
